<?php

/**
 * Created by PhpStorm.
 * User: dumbledore
 * Date: 2017/12/26
 * Time: 下午2:20
 */
class Order_model extends CI_Model
{

    public function __construct()
    {
        $this->load->database();
        $this->load->helper("common");
        $this->load->helper('json');
        $this->load->model('store_model');
        $this->load->model('customer_model');
    }

    //创建订单
    public function created_order($param)
    {
        $detail = json_decode($param['detail'], 'true');

        foreach ($detail as $key => $value) {
            $ShopSingleGoodsAllNum = $this->store_model->getShopGoodsAllNum($value['goods_id'], $param['shop_id']);
            if ($value['num'] > $ShopSingleGoodsAllNum) {
                send_json(array('code' => 4004, 'data' => '', 'msg' => '您所选的商品超过库存，请重新选择商品数量'));
            }
            $singleGoodsAllNum = $this->store_model->getAllGoodsNumByGoodsId($value['goods_id']);
            if ($value['num'] > $singleGoodsAllNum) {
                send_json(array('code' => 4004, 'data' => '', 'msg' => '您所选的商品超过库存，请重新选择商品数量'));
            }
        }
        $parent_shop_id              = $this->customer_model->customerFirstRegShopId($param['session_key']);
        $sale_rate                   = $this->store_model->getStoreInfo($param['shop_id'])['sale_rate'];
        $new_user_rate               = $this->store_model->getStoreInfo($parent_shop_id)['new_user_rate'];
        $order_bn                    = trade_no();
        $data_arr['order_bn']        = $order_bn;
        $data_arr['shop_id']         = $param['shop_id'];
        $data_arr['user_id']         = $this->customer_model->sessionKeyToUserId($param['session_key']);
        $data_arr['money']           = $param['money'];
        $data_arr['status']          = 0;
        $data_arr['created_at']      = date("Y-m-d H:i:s", time());
        $data_arr['type']            = 2;
        $data_arr['payment_method']  = 1;
        $data_arr['delivery_method'] = 1;

        $this->db->insert("app_order", $data_arr);
        $insert_id  = $this->db->insert_id();
        $order_info = array();
        if ($insert_id) {
            $commissionArr['order_id']               = $insert_id;
            $commissionArr['commission']             = $param['money'] * $sale_rate * 0.01;
            $commissionArr['parent_shop_id']         = $parent_shop_id;
            $commissionArr['parent_shop_commission'] = $param['money'] * $new_user_rate * 0.01;
            $this->db->insert("app_order_offline", $commissionArr);

            foreach ($detail as $key => $value) {
                $detail_arr['order_id'] = $insert_id;
                $detail_arr['goods_id'] = $value['goods_id'];
                $detail_arr['num']      = $value['num'];
                $this->db->insert("app_order_offline_detail", $detail_arr);
            }
            $order_info['money']    = $param['money'];
            $order_info['order_bn'] = $order_bn;
            $order_info['id']       = $insert_id;
            return $order_info;
        } else {
            return false;
        }

    }

    //订单列表
    public function getOrderList($session_key)
    {
        $user_id = $this->customer_model->sessionKeyToUserId($session_key);
        $where   = array('user_id' => $user_id, 'status !=' => 0, 'type' => 2);
        $list    = $this->db->select('id,money,status,refund_status,shop_id')->where($where)->from('app_order')->order_by('id', 'desc')->get()->result_array();
        foreach ($list as $key => $value) {
            $where               = array('order_id' => $value['id']);
            $list[$key]['order'] = $this->db->select('a.num as goods_num,b.title as goods_title,b.id as goods_id,b.goods_bn as goods_bn,b.pic_4 as goods_pic,b.price as goods_price')->where($where)->from('app_order_offline_detail a')
                ->join('app_goods b', 'a.goods_id = b.id')
                ->get()->result_array();
            $list[$key]['count']    = count($list[$key]['order']);
            $list[$key]['shopInfo'] = $this->store_model->getStoreInfo($value['shop_id']);
        }
        return $list;
    }

    //获取平台手机号码
    public function getServerPhone()
    {
        return $this->db->where(array('k' => 'phone'))->from('app_key_value')->get()->row_array()['v'];
    }

    //订单详情
    public function getOrderDetail($session_key, $id)
    {
        $user_id       = $this->customer_model->sessionKeyToUserId($session_key);
        $where         = array('id' => $id, 'user_id' => $user_id, 'type' => 2);
        $item          = $this->db->select('id,shop_id,order_bn,money,completed_at,status,refund_status,refunded_at')->where($where)->from('app_order')->get()->row_array();
        $where         = array('a.id' => $id, 'a.user_id' => $user_id);
        $item['order'] = $this->db->where($where)->select('b.title as title,b.pic_4 as pic,b.id as goods_id,b.goods_bn as goods_bn,b.price as price,b.id as goods_id,c.num as goods_num')->from('app_order a')
            ->join('app_order_offline_detail c', 'c.order_id=a.id')
            ->join('app_goods b', 'b.id=c.goods_id')
            ->get()->result_array();

        $item['shopInfo'] = $this->store_model->getStoreInfo($item['shop_id']);

        if ($item['order']) {
            return $item;
        } else {
            send_json(array('code' => 4004, 'data' => '', 'msg' => '订单不存在'));
        }
    }

    //退款
    public function refundOrder($param)
    {
        $user_id = $this->customer_model->sessionKeyToUserId($param['session_key']);
        $where   = array('user_id' => $user_id, 'order_id' => $param['id'], 'status' => 0);
        $refund  = $this->db->where($where)->from('app_refund')->get()->row_array();
        if ($refund) {
            send_json(array('code' => 0, 'data' => '', 'msg' => '您已申请退款，请等待审核'));
        } else {
            $data_arr['user_id']    = $user_id;
            $data_arr['order_id']   = $param['id'];
            $data_arr['remark']     = $param['remark'];
            $data_arr['detail']     = isset($param['detail']) ? $param['detail'] : '';
            $data_arr['pic_1']      = isset($param['pic_1']) ? $param['pic_1'] : '';
            $data_arr['pic_2']      = isset($param['pic_2']) ? $param['pic_2'] : '';
            $data_arr['pic_3']      = isset($param['pic_3']) ? $param['pic_3'] : '';
            $data_arr['status']     = 0;
            $data_arr['created_at'] = date("Y-m-d H:i:s", time());
            $res                    = $this->db->insert("app_refund", $data_arr);
            $insert_id              = $this->db->insert_id();
            if ($insert_id) {
                $where = array('id' => $insert_id);
                $this->db->where($where)->update('app_refund', array('refund_bn' => $user_bn = str_pad($insert_id, 7, "0", STR_PAD_LEFT)));
                $where = array('id' => $param['id']);
                $this->db->where($where)->update('app_order', array('refund_status' => 0));
                return true;
            } else {
                return false;
            }
        }
    }

    //获取订单详细信息
    public function getRefunDetail($param)
    {
        $user_id = $this->customer_model->sessionKeyToUserId($param['session_key']);
        $where   = array('user_id' => $user_id, 'order_id' => $param['order_id']);
        $detail  = $this->db->where($where)->from('app_refund')->order_by('id', 'desc')->limit(1)->get()->row_array();
        if ($detail) {
            return $detail;
        } else {
            return false;
        }
    }
}
